//
//  BQBaseRequest.m
//  honeycomb
//
//  Created by billionsfinance-resory on 16/2/26.
//  Copyright © 2016年 www.bqjr.cn. All rights reserved.
//

#import "BQBaseRequest.h"


static AFHTTPSessionManager *afManager;
@implementation BQBaseRequest

+ (void)initialize
{
    afManager = [AFHTTPSessionManager manager];
    afManager.responseSerializer.acceptableContentTypes = [afManager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    afManager.securityPolicy.allowInvalidCertificates = YES;
    [afManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    afManager.requestSerializer.timeoutInterval = 30.f;
    [afManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    afManager.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    securityPolicy.allowInvalidCertificates = NO;
    securityPolicy.validatesDomainName = NO;
    afManager.securityPolicy = securityPolicy;
    [afManager.reachabilityManager startMonitoring];
}

+ (void)getRequestWithBaseUrl:(NSString *)baseUrl
                 andParameter:(NSDictionary *)parameter
           andSuccessCallBack:(netWorkRequestSuccess)success
            andFailedCallBack:(netWorkRequestFailed)failed
{
    //监控网络
    [afManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:  // 局域网络,不花钱
                NSLog(@"WIFI");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:  //2G,3G,4G 花钱
                NSLog(@"自带网络");
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:    // 无连接
                [SVProgressHUD showErrorWithStatus:@"断网啦，请检查网络是否正常以及是否给本应用网络权限"];
                break;
            default:
                break;
        }
    }];
    
    [afManager GET:baseUrl parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        if (![responseObject isEqual:[NSNull null]]) {
            if([responseObject isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dataDic = responseObject;
                //如果ecode存在
                if([[dataDic allKeys] containsObject:@"ecode"])
                {
                    if(1 == [dataDic[@"ecode"] integerValue])
                    {
                        if(responseObject[@"data"])
                        {
                            success(responseObject[@"data"]);
                        }
                        else
                        {
                            success(dataDic);
                        }
                    }
                    else if(99 == [dataDic[@"ecode"] integerValue])
                    {
                        failed(@"token无效，请重新登录!");
                    }
                    else
                    {
                        if ([responseObject[@"msg"] isEqual:[NSNull null]]) {
                            failed(@"服务器返回未知错误");
                        }
                        else
                        {
                            failed(responseObject[@"msg"]);
                        }
                    }
                }
                else
                {//不存在直接返回
                    success(dataDic);
                }
            }
            else
            {
                //                    if([[responseObject allKeys] containsObject:@"data"])
                //                        success(responseObject[@"data"]);
                //                    else
                success(responseObject);
            }
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"服务器返回数据异常!"];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *errorLocalizedDescription = error.localizedDescription;
        if ([errorLocalizedDescription hasPrefix:@"请求超时"]) {
            failed(@"请求服务器超时,请稍后重试");
        }
        else if([errorLocalizedDescription hasPrefix:@"未能读取数据"])
        {
            failed(@"请求页面不存在,请稍后重试");
        }
        else
        {
            failed(@"连接服务器失败，请检查网络连接！");
        }
    }];

}

+ (void)postRequestWithBaseUrl:(NSString *)baseUrl
                  andParameter:(NSDictionary *)parameter
            andSuccessCallBack:(netWorkRequestSuccess)success
             andFailedCallBack:(netWorkRequestFailed)failed
{
    [afManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:  // 局域网络,不花钱
                NSLog(@"WIFI");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:  //2G,3G,4G 花钱
                NSLog(@"自带网络");
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:    // 无连接
                [SVProgressHUD showErrorWithStatus:@"断网啦，请检查网络是否正常以及是否给本应用网络权限"];
                return;
            default:
                break;
        }
    }];
    
    [afManager POST:baseUrl parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject isEqual:[NSNull null]]) {
            if([responseObject isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dataDic = responseObject;
                //如果ecode存在
                if([[dataDic allKeys] containsObject:@"ecode"])
                {
                    if(1 == [dataDic[@"ecode"] integerValue])
                    {
                        if(responseObject[@"data"])
                        {
                            success(responseObject[@"data"]);
                        }
                        else
                        {
                            success(dataDic);
                        }
                    }
                    else
                    {
                        if ([responseObject[@"message"] isEqual:[NSNull null]]) {
                            failed(@"服务器返回未知错误");
                        }
                        else
                        {
                            failed(responseObject[@"message"]);
                        }
                    }
                }
                else
                {//不存在直接返回
                    success(dataDic);
                }
            }
            else
            {
                success(responseObject);
            }
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"服务器返回数据异常!"];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *errorLocalizedDescription = error.localizedDescription;
        if ([errorLocalizedDescription hasPrefix:@"请求超时"]) {
            failed(@"请求服务器超时,请稍后重试");
        }
        else if([errorLocalizedDescription hasPrefix:@"未能读取数据"])
        {
            NSLog(@"error=%@",error);
            failed(@"请求页面不存在,请稍后重试");
        }
        else
        {
            NSLog(@"error=%@",error);
            failed(@"连接服务器失败，请检查网络连接！");
        }
    }];
}

+ (void)postImageDataWithBaseUrl:(NSString *)baseUrl
                    andParameter:(NSDictionary *)parameter
                andImageArr:(NSArray *)imageDataArrs
                      andSuccess:(netWorkRequestSuccess)success
                       andFailed:(netWorkRequestFailed)failed
{
    [afManager POST:baseUrl parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

@end
